package com.example.score.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class GZipUtils {

    /**
     * 解压
     * @param str 压缩后的字符串
     * @return 解压后的字符串
     * @throws IOException io异常
     */
    public static String decompress(String str) throws IOException {
        byte[] compressed = Base64.getDecoder().decode(str);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(compressed);
        try (GZIPInputStream gzip = new GZIPInputStream(byteIn);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzip.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toString("UTF-8");
        }
    }

    /**
     * 压缩
     * @param str 原字符串
     * @return 压缩后的字符串
     * @throws IOException io异常
     */
    public static String compressToBase64(String str) throws IOException {
        log.info("压缩前长度:{} ", str.getBytes(StandardCharsets.UTF_8).length);
        byte[] compressed = compress(str);
        String s = Base64.getEncoder().encodeToString(compressed);
        log.info("压缩后长度:{} ", s.length());
        return s;
    }


    private static byte[] compress(String str) throws IOException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(byteOut)) {
            gzip.write(str.getBytes(StandardCharsets.UTF_8));
        }
        return byteOut.toByteArray();
    }


}
